﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace Aribaccio.Custom
{
    public sealed class PagerBar : ContentControl
    {
        private readonly Style? _normalBtnStyle;
        private readonly Style? _holderBtnStyle;
        private readonly Style? _normalTxtStyle;
        private readonly PagerButton _btn1;
        private readonly PagerButton _btn2;
        private readonly PagerButton _btn3;
        private readonly PagerButton _btn4;
        private readonly PagerButton _btn5;
        private readonly PagerButton _btnStart;
        private readonly PagerButton _btnEnd;
        private readonly PagerButton _btnLast;
        private readonly PagerButton _btnNext;
        private readonly Label _tbkGoto;
        private readonly TextBox _tbxTargetPageIndex;
        private readonly List<FrameworkElement> _allElement;

        public int CurrentPageIndex { get { return (int)GetValue(CurrentPageIndexProperty); } set { SetValue(CurrentPageIndexProperty, value); } }
        public int PageSize { get { return (int)GetValue(PageSizeProperty); } set { SetValue(PageSizeProperty, value); } }
        public int PageCount { get { return (int)GetValue(PageCountProperty); } set { SetValue(PageCountProperty, value); } }

        public static readonly DependencyProperty CurrentPageIndexProperty = DependencyProperty.Register("CurrentPageIndex", typeof(int), typeof(PagerBar), new PropertyMetadata(-1, CurrentPageIndexPropertyChangedCallback));
        public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register("PageSize", typeof(int), typeof(PagerBar), new PropertyMetadata(10, PageSizePropertyChangedCallback));
        public static readonly DependencyProperty PageCountProperty = DependencyProperty.Register("PageCount", typeof(int), typeof(PagerBar), new PropertyMetadata(-1, PageCountPropertyChangedCallback));

        private static void CurrentPageIndexPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var pagerBar = d as PagerBar;
            pagerBar?.OnCurrentPageIndexChanged((int)e.NewValue);
        }
        private static void PageSizePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var pagerBar = d as PagerBar;
            pagerBar?.OnPageSizeChanged((int)e.NewValue);
        }
        private static void PageCountPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var pagerBar = d as PagerBar;
            pagerBar?.OnPageCountChanged((int)e.NewValue);
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public PagerBar()
        {
            //初始化定义样式
            this._normalBtnStyle = Application.Current.FindResource("PagerButtonStyle") as Style;
            this._holderBtnStyle = Application.Current.FindResource("PagerButtonHolderStyle") as Style;
            this._normalTxtStyle = Application.Current.FindResource("TextBoxStyle") as Style;
            //初始化定义按钮控件
            this._btn1 = new PagerButton() { Style = _normalBtnStyle };
            this._btn2 = new PagerButton() { Style = _normalBtnStyle };
            this._btn3 = new PagerButton() { Style = _normalBtnStyle };
            this._btn4 = new PagerButton() { Style = _normalBtnStyle };
            this._btn5 = new PagerButton() { Style = _normalBtnStyle };
            this._btnStart = new PagerButton() { Style = _normalBtnStyle, Content = "1" };
            this._btnEnd = new PagerButton() { Style = _normalBtnStyle, Content = $"{PageCount}" };
            this._btnLast = new PagerButton() { Style = _normalBtnStyle, Content = "<上一页" };
            this._btnNext = new PagerButton() { Style = _normalBtnStyle, Content = "下一页>" };
            //初始化定义跳转按钮模块
            this._tbkGoto = new Label() { Content = "转至：", Foreground = new SolidColorBrush(Colors.Black), FontSize = 14, HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center };
            this._tbxTargetPageIndex = new TextBox() { Style = _normalTxtStyle };
            //初始化定义板块
            var panel = new StackPanel() { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };
            panel.Children.Add(_btnLast);
            panel.Children.Add(_btnStart);
            panel.Children.Add(_btn1);
            panel.Children.Add(_btn2);
            panel.Children.Add(_btn3);
            panel.Children.Add(_btn4);
            panel.Children.Add(_btn5);
            panel.Children.Add(_btnEnd);
            panel.Children.Add(_btnNext);
            panel.Children.Add(_tbkGoto);
            panel.Children.Add(_tbxTargetPageIndex);
            this.AddChild(panel);
            //初始化定义元素集合
            _allElement = new List<FrameworkElement> { _btnLast, _btnStart, _btn1, _btn2, _btn3, _btn4, _btn5, _btnEnd, _btnNext, _tbkGoto, _tbxTargetPageIndex };
            //初始化定义按钮控件点击事件
            _btnLast.Click += (sender, args) => { if (CurrentPageIndex > 1) CurrentPageIndex--; };
            _btnStart.Click += (sender, args) => { CurrentPageIndex = 1; };
            _btn1.Click += (sender, args) => { CurrentPageIndex = Convert.ToInt32(_btn1.Content.ToString()); };
            _btn2.Click += (sender, args) => { CurrentPageIndex = Convert.ToInt32(_btn2.Content.ToString()); };
            _btn3.Click += (sender, args) => { CurrentPageIndex = Convert.ToInt32(_btn3.Content.ToString()); };
            _btn4.Click += (sender, args) => { CurrentPageIndex = Convert.ToInt32(_btn4.Content.ToString()); };
            _btn5.Click += (sender, args) => { CurrentPageIndex = Convert.ToInt32(_btn5.Content.ToString()); };
            _btnEnd.Click += (sender, args) => { CurrentPageIndex = PageCount; };
            _btnNext.Click += (sender, args) => { if (CurrentPageIndex < PageCount) CurrentPageIndex++; };
            //初始化定义跳转文本键盘事件
            _tbxTargetPageIndex.KeyDown += (sender, args) =>
            {
                if (args.Key == Key.Enter)
                {
                    if (int.TryParse(_tbxTargetPageIndex.Text, out var result))
                    {
                        if (result > PageCount || result < 1)
                        {
                            //System.Windows.Forms.MessageBox.Show("超出了页码范围", "错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        }
                        else
                        {
                            CurrentPageIndex = result;
                        }
                    }
                    else
                    {
                        //System.Windows.Forms.MessageBox.Show("请输入正确的页码格式", "错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                    _tbxTargetPageIndex.Text = string.Empty;
                }
            };
        }
        /// <summary>
        /// 重写应用模板
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
        }
        /// <summary>
        /// 页数改变事件
        /// </summary>
        /// <param name="argNewPageCount">新页数</param>
        private void OnPageCountChanged(int argNewPageCount)
        {
            if (_allElement == null || argNewPageCount == 0 || argNewPageCount == -1) { return; }
            switch (argNewPageCount)
            {
                case 1:
                    {
                        _allElement.ForEach(element => element.Visibility = Visibility.Collapsed);
                        _btnStart.Visibility = Visibility.Visible;
                        break;
                    }
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                    {
                        _btn1.Style = _normalBtnStyle;
                        _btn5.Style = _normalBtnStyle;
                        SetButtonsVisible(argNewPageCount);
                        break;
                    }
                default:
                    {
                        SetButtonsVisible(7);
                        _btnEnd.Content = $"{argNewPageCount}";
                        _btn1.Style = _normalBtnStyle;
                        _btn5.Style = _holderBtnStyle;
                        _allElement.GetRange(9, 2).ForEach(e => e.Visibility = Visibility.Visible);
                        break;
                    }
            }
        }
        /// <summary>
        /// 设置按钮可见性属性
        /// </summary>
        /// <param name="argCount"></param>
        private void SetButtonsVisible(int argCount)
        {
            //先全部设置：不显示元素，不为它的布局预留空间
            _allElement.ForEach(element => element.Visibility = Visibility.Collapsed);
            //再设置：显示元素
            var visibleList = _allElement.GetRange(1, argCount);
            for (var i = 0; i < visibleList.Count; i++)
            {
                visibleList[i].Visibility = Visibility.Visible;
                if (visibleList[i] is Button btn)
                {
                    btn.Content = $"{i + 1}";
                }
            }
            _btnLast.Visibility = Visibility;
            _btnNext.Visibility = Visibility;
        }
        /// <summary>
        /// 每页显示数量改变事件
        /// </summary>
        /// <param name="argNewValue">新每页页数值</param>
        private void OnPageSizeChanged(int argNewValue)
        {

        }
        /// <summary>
        /// 当前页数改变事件
        /// </summary>
        /// <param name="argCurrentIndex">当前页数索引值</param>
        private void OnCurrentPageIndexChanged(int argCurrentIndex)
        {
            if (_allElement == null || argCurrentIndex > PageCount) { return; }
            //获取设置前面9个按钮元素，
            foreach (var frameworkElement in _allElement.Take(9))
            {
                //判断是否按钮元素
                if (frameworkElement is PagerButton btn)
                {
                    //设置非活动状态
                    btn.IsActive = false;
                }
            }
            //设置当前页按钮元素
            if (PageCount <= 7)
            {
                if (_allElement[argCurrentIndex] is PagerButton pb) { pb.IsActive = true; }
            }
            else
            {
                if (argCurrentIndex < 4)
                {
                    if (_allElement[argCurrentIndex] is PagerButton btn)
                    {
                        btn.IsActive = true;
                    }
                    _btn1.Style = _normalBtnStyle;
                    _btn5.Style = _holderBtnStyle;
                    _btn1.Content = $"2";
                    _btn2.Content = $"3";
                    _btn3.Content = $"4";
                    _btn4.Content = $"5";
                }
                else if (argCurrentIndex == 4)
                {
                    _btn3.IsActive = true;
                    _btn1.Style = _normalBtnStyle;
                    _btn5.Style = _holderBtnStyle;
                    SetButtonText(argCurrentIndex);
                }
                else if (argCurrentIndex > 4 && argCurrentIndex < PageCount - 3)
                {
                    _btn3.IsActive = true;
                    _btn1.Style = _holderBtnStyle;
                    _btn5.Style = _holderBtnStyle;
                    SetButtonText(argCurrentIndex);
                }
                else if (argCurrentIndex == PageCount - 3)
                {
                    _btn3.IsActive = true;
                    _btn1.Style = _holderBtnStyle;
                    _btn5.Style = _normalBtnStyle;
                    SetButtonText(argCurrentIndex);
                }
                else
                {
                    if (_allElement[7 - (PageCount - argCurrentIndex)] is PagerButton btn)
                    {
                        btn.IsActive = true;
                    }
                    _btn1.Style = _holderBtnStyle;
                    _btn5.Style = _normalBtnStyle;
                    _btn2.Content = $"{PageCount - 4}";
                    _btn3.Content = $"{PageCount - 3}";
                    _btn4.Content = $"{PageCount - 2}";
                    _btn5.Content = $"{PageCount - 1}";
                }
            }
            //设置上一页，下一页是否有效[及灰色不可点击]
            if (argCurrentIndex == 1)
            {
                _btnLast.IsEnabled = false;
                _btnNext.IsEnabled = true;
            }
            else if (argCurrentIndex == PageCount)
            {
                _btnLast.IsEnabled = true;
                _btnNext.IsEnabled = false;
            }
            else
            {
                _btnLast.IsEnabled = true;
                _btnNext.IsEnabled = true;
            }
        }
        /// <summary>
        /// 设置当前按钮元素内容
        /// </summary>
        /// <param name="argCurrentIndex">当前页数索引值</param>
        private void SetButtonText(int argCurrentIndex)
        {
            _btn1.Content = $"{argCurrentIndex - 2}";
            _btn2.Content = $"{argCurrentIndex - 1}";
            _btn3.Content = $"{argCurrentIndex - 0}";
            _btn4.Content = $"{argCurrentIndex + 1}";
            _btn5.Content = $"{argCurrentIndex + 2}";
        }
    }
}
